<template>
    <div class="chat-container">
      <!-- 连接控制 -->
      <div class="connection-control">
        <el-input
          v-model="sid"
          placeholder="输入用户ID"
          style="width: 200px; margin-right: 10px"
          :disabled="sid"
        />
        
        <el-button
          type="primary"
          :icon="Connection"
          @click="connect"
          :disabled="isConnected"
        >
          {{ isConnected ? '已连接deepseek' : '连接deepseek' }}
        </el-button>
        <!--<span class="online-count">正在使用的人数：{{ onlineCount }}</span>-->
      </div>
  
      <!-- 聊天消息区域 -->
      <div class="chat-box">
        <div
          v-for="(msg, index) in messages"
          :key="index"
          class="message-item"
          :class="{ 'own-message': msg.isOwn }"
        >
          <div class="message-header">
            <span class="sender">{{ msg.sender }}</span>
            <span class="time">{{ formatTime(msg.timestamp) }}</span>
          </div>
          <!--<div class="message-content" >{{ msg.content }}</div>-->

          <div class="message-content" v-html="msg.formattedContent"></div>
        </div>

      <div v-if="isWaitingForReply" class="loading-indicator">
        <div class="dot-flashing"></div>
        <span class="loading-text">思考中...</span>
      </div>

      </div>
  
      <!-- 消息发送区域 -->
      <div class="message-input">
        <el-input
          v-model="inputMessage"
          type="textarea"
          :rows="3"
          placeholder="输入消息"
          @keyup.enter.native="sendMessage"
        />
        <el-button
          type="primary"
          @click="sendMessage"
          :disabled="!isConnected"
          style="margin-top: 10px"
        >
          发送
        </el-button>
      </div>
    </div>
  </template>
  
  <script setup>
  import { nextTick } from 'vue' // 添加这行
  import { ref, onUnmounted } from 'vue'
  import { ElMessage } from 'element-plus'
  import { Connection } from '@element-plus/icons-vue'
  import useUserStore from '@/store/modules/user'
  import { parseMarkdown } from '@/utils/markdownParser' // 新增导入

  // 新增响应式状态
  const isWaitingForReply = ref(false)
  const isConnected = ref(false)
  const userStore = useUserStore()
  const sid = userStore.name
  const onlineCount = ref(0)
  const inputMessage = ref('')
  const messages = ref([])
  let websocket = null

  // 格式化时间
  const formatTime = (timestamp) => {
    return new Date(timestamp).toLocaleTimeString()
  }
  
  // 建立 WebSocket 连接
  const connect = () => {
    if (isConnected.value) return
  
    websocket = new WebSocket(`wss://www.yjklxw.xyz/ws/${sid}`)
    websocket.onopen = () => {
      isConnected.value = true
      ElMessage.success('连接成功')
    }
  
    websocket.onmessage = (event) => {
    try {
        const message = JSON.parse(event.data);
        
        // 系统消息
        if (message.content === '连接成功') {
            onlineCount.value = message.onlineCount
            return
        }

        // 用户消息处理
        if (message.type === 'user_message') {
            messages.value.push({
                sender: 'user',
                content: message.content,
                timestamp: message.timestamp,
                isOwn: true,
                formattedContent: parseMarkdown(message.content)
            });
        }
        
        // AI消息处理
        if (message.type === 'ai_response') {
            messages.value.push({
                sender: 'DeepSeek:',
                content: message.content,
                timestamp: message.timestamp,
                isOwn: false,
                formattedContent: parseMarkdown(message.content)
            });
        }
        
        scrollToBottom();
        isWaitingForReply.value = false // 收到响应后停止加载
    } catch (e) {
        isWaitingForReply.value = false // 出错时也停止加载
        console.error('消息解析失败:', e);
    }
}



  
    websocket.onerror = (error) => {
      isWaitingForReply.value = false
      ElMessage.error('连接错误: ' + error.message)
    }
  
    websocket.onclose = () => {
      isWaitingForReply.value = false
      isConnected.value = false
      ElMessage.warning('连接已关闭')
    }
  }
  
  // 发送消息
  const sendMessage = () => {
  if (!inputMessage.value.trim()) return

  isWaitingForReply.value = true // 开始等待
  console.log('发送时状态:', isWaitingForReply.value) 
  const message = {
    type: "user_message",
    content: inputMessage.value,
    timestamp: new Date().getTime()
  }

  websocket.send(JSON.stringify(message))
  inputMessage.value = ''
  scrollToBottom()
}
  
  // 自动滚动到底部
  const scrollToBottom = () => {
    nextTick(() => {
      const container = document.querySelector('.chat-box')
      if (container) {
        container.scrollTop = container.scrollHeight
      }
    })
  }
  
  // 关闭连接
  onUnmounted(() => {
    if (websocket) {
      websocket.close()
    }
  })


  // 前端添加心跳
//setInterval(() => {
 // if (isConnected.value) {
 //   websocket.send("xintiao")
 // }
//}, 60000)
  </script>
  
<style scoped>

/* 加载动画样式 */
.loading-indicator {
  display: flex;
  align-items: center;
  padding: 12px;
  margin: 10px 0;
  background-color: #f5f7fa;
  border-radius: 8px;
  max-width: 120px;
  position: sticky;
  bottom: 10px;
  z-index: 999; /* 新增层级 */
}

.dot-flashing {
  position: relative;
  width: 10px;
  height: 10px;
  border-radius: 5px;
  background-color: #409eff;
  animation: global(dotFlashing) 1s infinite linear alternate !important;
  animation-delay: .5s;
}

.dot-flashing::before,
.dot-flashing::after {
  content: '';
  position: absolute;
  top: 0;
  width: 10px;
  height: 10px;
  border-radius: 5px;
  background-color: #409eff;
}

.dot-flashing::before {
  left: -15px;
  animation: global(dotFlashing) 1s infinite alternate !important;
}

.dot-flashing::after {
  left: 15px;
  animation: global(dotFlashing) 1s infinite alternate !important;
  animation-delay: 1s;
}

.loading-text {
  margin-left: 8px;
  color: #606266;
  font-size: 0.9em;
}

  .chat-container {
    max-width: 800px;
    margin: 20px auto;
    padding: 20px;
    border: 1px solid #ebeef5;
    border-radius: 4px;
  }
  
  .connection-control {
    display: flex;
    align-items: center;
    margin-bottom: 20px;
  }
  
  .online-count {
    margin-left: 20px;
    color: #666;
  }
  
  .chat-box {
    height: 550px;
    overflow-y: auto;
    border: 1px solid #ebeef5;
    border-radius: 4px;
    padding: 10px;
    margin-bottom: 20px;
  }
  
  .message-item {
    margin: 10px 0;
    padding: 10px;
    border-radius: 4px;
    background-color: #f5f7fa;
    max-width: 80%;
  }
  
  .message-item.own-message {
    margin-left: auto;
    background-color: #ecf5ff;
  }
  
  .message-header {
    display: flex;
    justify-content: space-between;
    margin-bottom: 5px;
    font-size: 0.9em;
  }
  
  .sender {
    color: #409eff;
    font-weight: bold;
  }
  
  .time {
    color: #909399;
  }
  
  .message-content {
    word-break: break-word;
  }
  
  .message-input {
    position: relative;
  }

/* 添加Markdown内容样式 */
.message-content :deep() {
  h1, h2, h3, h4 {
    margin: 0.8em 0;
    font-weight: bold;
  }

  ul, ol {
    padding-left: 2em;
    margin: 0.5em 0;
  }

  li {
    margin: 0.3em 0;
    line-height: 1.6;
  }

  hr {
    margin: 1em 0;
    border: 0;
    border-top: 1px solid #ddd;
  }

  p {
    margin: 0.5em 0;
    line-height: 1.6;
  }

  strong {
    font-weight: bold;
  }

  em {
    font-style: italic;
  }
}

</style>


<style>
@keyframes dotFlashing {
  0% { background-color: #409eff; }
  50%, 100% { background-color: rgba(64, 158, 255, 0.2); }
}
</style>